<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use think\Db;
/**
 * 邮箱验证码接口
 */
class Wechat extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $this->success('wechat_index');
    }


    //同步家校通讯录年级部门列表
    public function grade_forumbee()
    {
        $result = false;
        Db::startTrans();
        $Dao = new \app\common\logic\Dao();
        try {
            $grade = Db::name('grade')->select();

//            foreach ($grade as $item){
                $result = $Dao->refreshDepartment(8);
                foreach ($result['departments'] as $k => $v){
                    //1班级 2年级
                    if ($v['type'] == 1) {
                        $str = str_replace(['高一','高二','高三','班',' '],'',$v['name']);

                        if (!in_array($v['parentid'],[8,9,457])) {
                            continue;
                        }
                        if ($v['parentid'] == 9) {
                            $name = "高三（{$str}）";
                            $grade_id = 2;
                            $wechat_id = 9;
                        }
                        if ($v['parentid'] == 8) {
                            $name = "高二（{$str}）";
                            $grade_id = 3;
                            $wechat_id = 8;
                        }
                        if ($v['parentid'] == 457) {
                            $name = "高一（{$str}）";
                            $grade_id = 1;
                            $wechat_id = 457;
                        }

                        $class = Db::name('grade_class')->where(['name'=>$name,'grade_id'=>$grade_id])->find();

//                        dump($class,1,"['name'=>{$name},'grade_id'=>{$item['id']},'wechat_id'=>{$v['id']},'wechat_parent_id'=>{$v['parentid']}]");
                        if ($class['id'] == 59){
                            dump(['name'=>$name,'grade_id'=>$grade_id]);
                            dump($v);
                        }

                        if ($class){
                            //dump(array_merge(['name'=>$name],['id'=>$class['id']],['wechat_id'=>$v['id'],'wechat_parent_id'=>$v['parentid']],['wechat_id'=>$v['id'],'wechat_parent_id'=>$v['parentid']]));
//                                Db::name('grade_class')->where('id',$class['id'])->update(['wechat_id'=>$v['id'],'wechat_parent_id'=>$v['parentid']]);
                        }else{
//                                dump("{$name}不存在",1,$item['id']);
                            //不存在
                            //ppp($v,$item,"不存在:".Db::name('grade_class')->where(['name'=>$name,'grade_id'=>$item['id']])->fetchSql()->find());
                        }
//

                    }elseif ($v['type'] == 2) {
//dump($v);
                    }
                }


//            }
die;
            dump($result,1,'家校通讯录');die;
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error('系统错误','',$e->getMessage());
        }

        if ($result !== true) {
//            Db::commit();
            $this->error($result,'',$Dao->result);
        }else{
            $this->success('更新成功');
        }
    }


    //同步通讯录部门列表
    public function department_forumbee()
    {
        $result = false;
        Db::startTrans();
        $Dao = new \app\common\logic\Dao();
        try {


            $department = $Dao->departmentListGet();

            foreach ($department['department'] as $key => $value) {

                $result = $Dao->departmenUserListGet($value['id']);

                dump($result);
            }

die;

            dump($result,1,'通讯录');die;
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error('系统错误','',$e->getMessage());
        }

        if ($result !== true) {
            Db::commit();
            $this->error($result,'',$Dao->result);
        }else{
            $this->success('更新成功');
        }
    }


    //同步通讯录部门列表
    public function department_user(int $department = null)
    {
        $result = false;
        Db::startTrans();
        $Dao = new \app\common\logic\Dao();
        try {
            $result = $Dao->departmenUserListGet($department);

            ppp($result);


            dump($result,1,'通讯录成员');die;
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error('系统错误','',$e->getMessage());
        }

        if ($result !== true) {
            Db::commit();
            $this->error($result,'',$Dao->result);
        }else{
            $this->success('更新成功');
        }
    }



    





    //-------------------------------------------------------------ok--------------

    //一键同步年级数据
    public function grade()
    {
        $result = false;
        Db::startTrans();
        $Dao = null;
        try {
            //腾讯标准年级限定-高中
            $wechat_standard = [91,92,93,94];
            $Dao = new \app\common\logic\Dao();
            $grade = Db::name('grade')->field('id,name,wechat_id')->select();
            $grade_wechat_id = array_column($grade,'wechat_id');
            $res = $Dao->refreshDepartment();
            if(!empty($res['departments'])) {
                $insert = [];
                $update = [];
                $wechat_id = [];
                $time = time();
                $school_campus_id = campus_id(1);
                $year_id = year_id(1);
                foreach ($res['departments'] as $k => $v) {
                    //1班级 2年级
                    if ($v['type'] == 2 && isset($v['standard_grade']) && in_array($v['standard_grade'], $wechat_standard)) {
                        if (in_array($v['id'], $grade_wechat_id)) {
                            //更新
                            array_push($update, "WHEN {$v['id']} THEN '{$v['name']}'");
                            array_push($wechat_id, $v['id']);
                        } else {
                            //插入
                            array_push($insert, " ('{$v['name']}',{$school_campus_id},{$year_id},1,{$time},{$v['id']})");
                        }
                    }
                }

                if ($insert) {
                    $insert = implode(',', $insert);
                    $sql = "INSERT INTO `fa_grade` (`name`,`school_campus_id`,`year_id`,`class_hour`,`createtime`,`wechat_id`)  VALUES {$insert}";

                }

                if ($update) {
                    $wechat_id = implode(',', $wechat_id);
                    $update = implode(' ', $update);
                    $sql = "UPDATE `fa_grade` SET name = (CASE `wechat_id` {$update} END), `updatetime` = {$time} WHERE `wechat_id` IN ({$wechat_id})";
                }


                $result = Db::query($sql);
            }
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error('系统错误','',$e->getMessage());
        } finally {
            unset($Dao);
        }

    }




    //一键同步班级数据
    public function class()
    {
        $result = false;
        Db::startTrans();
        $Dao = null;
        try {
            //腾讯标准年级限定-高中
            $Dao = new \app\common\logic\Dao();
            $grade = Db::name('grade')->field('id,name,wechat_id')->select();
            $class = Db::name('grade_class')->field('id,name,wechat_id')->select();
            $grade_wechat_id = array_column($grade,'wechat_id');
            $class_wechat_id = array_column($class,'wechat_id');
            $res = $Dao->refreshDepartment();


            $class_name_array = [];
            foreach ($grade as $v){
                $class_name_array[$v['wechat_id']] = $v['name'];
            }


            if(!empty($res['departments'])) {
                $insert = [];
                $update = [];
                $class_name = [];
                $wechat_id = [];
                $time = time();
                $school_campus_id = campus_id(1);
                $year_id = year_id(1);
                $semester_id = semester_id(1);

                $deal = [];
                $grade_id = [];
                foreach ($res['departments'] as $k => $v) {
                    //1班级 2年级
                    if ($v['type'] == 1 && in_array($v['parentid'],$grade_wechat_id)) {
                        if (in_array($v['id'], $class_wechat_id)) {
                            //更新
                            array_push($update, "WHEN {$v['id']} THEN '{$v['name']}'");
                            array_push($class_name, "WHEN {$v['id']} THEN '{$class_name_array[$v['parentid']]}{$v['name']}'");
                            array_push($wechat_id, $v['id']);
                        } else {
                            if(!isset($grade_id[$v['id']])) {
                                foreach ($grade as $item) {
                                    if ($item['wechat_id'] == $v['parentid']){
                                        $grade_id[$v['id']] = $item['id'];
                                        break;
                                    }
                                }

                            }
                            $teacher_one = 0;
                            $teacher_two = 0;
                            //插入
                            array_push($insert, " ({$semester_id},{$grade_id[$v['id']]},'{$v['name']}',{$school_campus_id},50,$teacher_one,$teacher_two,{$time},{$year_id},{$v['id']},{$v['parentid']})");
                        }

                    }
                }
                if ($insert) {
                    $insert = implode(',', $insert);
                    $sql = "INSERT INTO `fa_grade_class` (`semester_id`,`grade_id`,`name`,`school_campus_id`,`max`,`teacher_one`,`teacher_two`,`createtime`,`year_id`,`wechat_id`,`wechat_parent_id`)  VALUES {$insert}";
//                    dump($sql);
                    //$result = Db::query($sql);
                }


                if ($update) {
                    $wechat_id = implode(',', $wechat_id);
                    $update = implode(' ', $update);
                    $class_name = implode(' ', $class_name);
                    $sql = "UPDATE `fa_grade_class` SET name = (CASE `wechat_id` {$update} END),class_name = (CASE `wechat_id` {$class_name} END), `updatetime` = {$time} WHERE `wechat_id` IN ({$wechat_id})";
                    $result = Db::query($sql);
//                    ppp( $sql);
                }


//
            }
            Db::commit();
        } catch (\Throwable $e) {
//            dump($e->getLine());
//            dump($e->getFile());
            Db::rollback();
            $this->error('系统错误','',$e->getMessage());
        } finally {
            unset($Dao);
        }

    }








    public function grade_insert()
    {
        $result = false;
        Db::startTrans();
        $Dao = null;
        try {
            //腾讯标准年级限定-高中
            $wechat_standard = [91,92,93,94];
            $Dao = new \app\common\logic\Dao();

            $res = $Dao->refreshDepartment();
            if(!empty($res['departments'])) {
                $insert = [];
                $update = [];
                $wechat_id = [];
                $time = time();
                $school_campus_id = campus_id(1);
                $year_id = year_id(1);
                foreach ($res['departments'] as $k => $v) {
                    //1班级 2年级
                    if ($v['type'] == 2 && isset($v['standard_grade']) && in_array($v['standard_grade'], $wechat_standard)) {
                        //插入
                        array_push($insert, " ('{$v['name']}',{$school_campus_id},{$year_id},1,{$time},{$v['id']})");
                    }
                }

                if ($insert) {
                    $insert = implode(',', $insert);
                    $sql = "INSERT INTO `fa_grade` (`name`,`school_campus_id`,`year_id`,`class_hour`,`createtime`,`wechat_id`)  VALUES {$insert}";
                }

                

                $result = Db::query($sql);
            }
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error('系统错误','',$e->getMessage());
        } finally {
            unset($Dao);
        }

    }




    public function class_insert()
    {
        $result = false;
        Db::startTrans();
        $Dao = null;
        try {
            //腾讯标准年级限定-高中
            $Dao = new \app\common\logic\Dao();
            $grade = Db::name('grade')->field('id,name,wechat_id')->select();

            /*dump($grade);
            $res = $Dao->refreshDepartment(9);

            ppp($res);
*/            $time = time();
            $school_campus_id = campus_id(1);
            $year_id = year_id(1);
            $semester_id = semester_id(1);
                    $i = 0;
                    $insert = [];
                    $update = [];
                    $wechat_id = [];
            foreach ($grade as $k => $vs) {
                $res = $Dao->refreshDepartment($vs['wechat_id']);

                if(!empty($res['departments'])) {
                    
                    

                    $deal = [];
                    foreach ($res['departments'] as $k => $v) {
                        $teacher_one = 0;
                        $teacher_two = 0;
                        $teacher_one_name = '';
                        $teacher_two_name = '';
                        //1班级 2年级
                        if ($v['type'] == 1) {
                            if (!empty($v['department_admins'])) {
                                foreach ($v['department_admins'] as $key => $val) {
                                    if ($val['type'] == 3) {
                                        $user = Db::name('user')->where('UserId',$val['userid'])->field('id,username')->find();
                                        
                                        if (isset($user['id']) && $teacher_one === 0) {
                                            $teacher_one = $user['id'];
                                            $teacher_one_name = $user['username'];
                                        }

                                        if (isset($user['id']) && $teacher_two === 0) {
                                            $teacher_two = $user['id'];
                                            $teacher_two_name = $user['username'];
                                        }
                                        
                                    }
                                }
                            }

                            $i++;
                            array_push($insert, " ({$semester_id},{$vs['id']},'{$v['name']}',{$school_campus_id},50,{$teacher_one},'{$teacher_one_name}',{$teacher_two},'{$teacher_two_name}',{$time},{$year_id},{$v['id']},{$v['parentid']})");
                        }
                    }
                }
            }

            
            if ($insert) {
                $insert = implode(',', $insert);
                $sql = "INSERT INTO `fa_grade_class` (`semester_id`,`grade_id`,`name`,`school_campus_id`,`max`,`teacher_one`,`teacher_one_name`,`teacher_two`,`teacher_two_name`,`createtime`,`year_id`,`wechat_id`,`wechat_parent_id`)  VALUES {$insert}";

                $result = Db::query($sql);
            }
            
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            dump($e->getLine());
            dump($e->getFile());
            $this->error('系统错误','',$e->getMessage());
        } finally {
            unset($Dao);
        }

    }







    //同步通讯录部门列表-家校通讯录
    public function department_school(int $department = null)
    {
        $result = false;
        Db::startTrans();
        $Dao = new \app\common\logic\Dao();
        try {
            $class = Db::name('grade_class')->select();
            
            foreach ($class as $item){
                $result = $Dao->refreshStudentList($item['wechat_id']);


                if (!empty($result['students'])) {
                    foreach ($result['students'] as $v){
                        dump(Db::name('student_user')->fetchSql()->insertGetId(['nickname'=>$v['name'],'username'=>$v['name'],'status'=>1,'wechat_id'=>$v['student_userid']]),1,11111);
                        $id = Db::name('student_user')->insertGetId(['nickname'=>$v['name'],'username'=>$v['name'],'status'=>1,'wechat_id'=>$v['student_userid']]);

                        dump(Db::name('class_student_distribution')->fetchSql()->insert(['campus_id'=>campus_id(),'year_id'=>year_id(),'semester_id'=>semester_id(),'grade_id'=>$item['grade_id'],'student_id'=>$id,'class_id'=>$item['id'],'createtime'=>time(),'wechat_id'=>$v['student_userid']]),1,11111);
                        Db::name('class_student_distribution')->insert(['campus_id'=>campus_id(),'year_id'=>year_id(),'semester_id'=>semester_id(),'grade_id'=>$item['grade_id'],'student_id'=>$id,'class_id'=>$item['id'],'createtime'=>time(),'wechat_id'=>$v['student_userid']]);
                        

                        foreach ($v['parents'] as $parent){
                            dump(Db::name('student_parent')->fetchSql()->insert(['student_userid'=>$id,'nickname'=>"{$v['name']}{$parent['relation']}",'relation'=>$parent['relation'],'is_subscribe'=>$parent['is_subscribe'] ?? 0,'wechat_parent_userid'=>$parent['parent_userid'],'wechat_student_userid'=>$v['student_userid'],'wechat_external_userid'=>$parent['external_userid'] ?? '','mobile'=>$parent['mobile'] ?? '']),1,33333);
                            Db::name('student_parent')->insert(['student_userid'=>$id,'nickname'=>"{$v['name']}{$parent['relation']}",'relation'=>$parent['relation'],'is_subscribe'=>$parent['is_subscribe'] ?? 0,'wechat_parent_userid'=>$parent['parent_userid'],'wechat_student_userid'=>$v['student_userid'],'wechat_external_userid'=>$parent['external_userid'] ?? '','mobile'=>$parent['mobile'] ?? '']);
                        }
//        die;
                    }

                }
            }

            // dump($result,1,'家校通讯录成员');die;
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            dump($e->getMessage());
            dump($e->getFile());
            dump($e->getLine());die;
            
            $this->error('系统错误','',$e->getMessage());
        }

        if ($result !== true) {
            $this->error($result,'',$Dao->result);
        }else{
            $this->success('更新成功');
        }
    }



    //学籍处理
    public function student()
    {
        $list = Db::name('student_user')->select();
        foreach ($list as $item){
            Db::name('student')->insert([
                'user_id'               =>$item['id'],
                'campus_id'             =>1,
                'data_source'           =>1,
                'ent_year'              =>2021,
                'realname'              =>$item['username'],
                'sex'                   =>1,
                'stunature_status'      =>1,
                'status'                =>1,
                'identity'              =>1,
                'nation'                =>'未知',
                'native_place'          =>'北京',
                'native_place_province' =>1,
                'native_place_city'     =>2,
                'address'               =>'中国',
                'relationship1'         =>1,
                'createtime'            =>time(),
                'student_num'           =>"2021".random_int(10000,99999)
            ]);
        }

    }




}
